<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/7
 * Time: 14:30
 */

namespace app\index\controller;


use jianyan\excel\Excel;
use Protocol\Curl;
use think\Db;

class GetInfo extends Common
{

    /**
     * @return array
     * @content  管理制度
     */
    function ruleInfo()
    {
        $info = Db::table("application")->field('id,application_title title,application_order,application_context content')->where(array("application_class" => "train"))->order("application_order asc")->select();
        return array('status' => true, 'data' => $info);
    }

    /**
     * @return array
     * @content 首页消息通知
     */
    function homeNotice()
    {
//        $info = "所有门店员工对待所有客户需保持良好的服务态度，行走过程中应礼让顾客先行，并微笑打招呼说“您好！”所有基层服务岗位员工，若在本月工作中，满足以上优秀员工评选标准，并结合服务评论分值，可参与本月优秀员工评选，单独门店内月度评选2名优秀员工，月度评为优秀员工的给予200元现金奖励，当月工资中体现。";
        $time = date('Y-m-d H:i:s');
        $info = Db::table('notice')->field('content')->where(array('accepter' => 2,'is_del'=>2))
            ->where("start_time <= '" . $time . "' and end_time >= '" . $time . "'")->find();
        if(!empty($info)){
            $info = $info['content'];
        }else{
            $info = '';
        }
        return array('status' => true, 'data' => $info);
    }

    /**
     * @return array|mixed|string
     * @content 我的二维码
     */
    function MyQRCode()
    {
        $img_info = input('post.img_info');
        if (empty($img_info)) {
            return array('status' => false, 'msg' => '上传图片信息不能为空');
        }
        $filename = 'biz-' . $this->bizId;
        if (!empty($this->employeeId)) {
            $filename = 'staff-' . $this->employeeId;
        }
        if (!file_exists(ROOT_PATH . 'QRCode/' . $filename)) {
            $filename = uploadBase($img_info, true, $filename);
        } else {
            $filename .= '.jpeg';
        }
        if (is_array($filename)) {
            return $filename;
        }
        return array('status' => true, 'imgUrl' => imgUrl('QRCode/' . $filename, true));
    }

    /**
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @content 工资表导出
     */
    function PayrollExport()
    {
        $month = input('post.month');
        $info = $this->_Redis->hGetJson('salary' . strval($this->bizId), $month);
        if (empty($info)) {
            return array('status' => false, 'msg' => '信息为空');
        }
        $header = [
            ['员工姓名', 'employee_name'], // 规则不填默认text
            ['岗位', 'jobs_info', 'text'],
            ['基础工资', 'basic_salary', 'text'],
            ['满勤工资', 'full_salary'],
            ['出勤天数', 'pract_att_days'],
            ['实际工资', 'real'],
            ['提成', 'commission_salary'],
            ['合计工资', 'total'],
            ['罚款', 'deduct_salary'],
            ['实际发放', 'count']
        ];
        Excel::exportData($info, $header, '员工工资表-' . $month, 'xlsx', ROOT_PATH . 'salaryExcel/' . '员工工资表-' . $month . '.xlsx');
        return array('status' => true, 'url' => imgUrl('salaryExcel/' . '员工工资表-' . $month . '.xlsx', true), 'filename' => 'salaryExcel/' . '员工工资表-' . $month . '.xlsx');
    }

    /**
     * @content 工资表删除
     */
    function PayrollDel()
    {
        $path = input('post.filename');
        if (!empty($path)) {
            if (file_exists(ROOT_PATH . $path)) {
                @unlink(ROOT_PATH . $path);
            }
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 协议查询
     */
    function protocol()
    {
        # cooperation_ecars=>关于"E联车服"   cooperation_agreement=>合作协议
        $mark = input('post.mark');
        $info = $this->_Redis->hGetJson('protocol', $mark);
//        if($mark=='bizprotocol'){
//            $info = [];
//        }
        if (empty($info)) {
            $info = Db::table("application")->field('id,application_title title,application_context content,application_uri')
                ->where(array("application_class" => "protocol", 'application_mark' => $mark))->find();
            if (!empty($info)) {
                $info['content'] = str_replace('src="/Resource/upload/', 'src="' . config('ecarcoo.EcarsImgUrl'), $info['content']);
                $info['content'] = str_replace('px;', 'rpx;', $info['content']);
                $info['content'] = str_replace('px"', 'rpx"', $info['content']);
            }
            $this->_Redis->hSetJson('protocol', $mark, $info);
        }
        /*if($mark=='cooperation_ecars'){
            $info['application_uri']= 'http://www.elianchefu.com';
        }*/
        return array('status' => true, 'data' => $info);
    }

    /**
     * @return array
     * @content 苹果二手车
     */
    function usedCar()
    {
        return array('status' => true, 'imgUrl' => imgUrl('static/advertisement/usedCar.png', true),'version'=>'1.1.8');
    }

    function getTopics()
    {
        # 历史话题
        $info = Db::table('biz_topic')->field('topics title,status')
            ->where(array('b_id' => $this->bizId, 'status' => 0))
            ->select();
        # 正在使用的话题
        $tipsArr = Db::table('biz_topic')
            ->where(array('b_id' => $this->bizId, 'status' => 1))
            ->column('topics');
        # 话题数量
        $topicsNum = 10;
        $tipsNum_show = 3;
        # 视频
        $video_info = Db::table('biz_video')->where(array('b_id' => $this->bizId))->limit(3)->column('video_url');

        $topic = ['E联车服'];
        return array('status' => true, 'data' => $info, 'tipsArr' => $tipsArr,
            'topicsNum' => $topicsNum, 'tipsNum_show' => $tipsNum_show,
            'video_info' => $video_info,'topic'=>$topic
        );
    }
    function setTopics()
    {
        $info = input('post.info');
        $tipsArr = Db::table('biz_topic')->field('id,topics')
            ->where(array('b_id' => $this->bizId, 'status' => 1))
            ->select();
        $delArr = array();
        $info_new = array();
        if (!empty($tipsArr)) {
            foreach ($tipsArr as $k => $v) {
                if (!in_array($v['topics'], $info)) {
                    array_push($delArr, $v['id']);
                } else {
                    array_push($info_new, $v['topics']);
                }
            }
        }
        $updateArr = array();
        $tipsArrs = Db::table('biz_topic')->field('id,topics')
            ->where(array('b_id' => $this->bizId, 'status' => 0))
            ->select();
        if (!empty($tipsArrs)) {
            foreach ($tipsArrs as $k => $v) {
                if (in_array($v['topics'], $info)) {
                    array_push($updateArr, $v['id']);
                    array_push($info_new, $v['topics']);
                }
            }
        }
        if (!empty($delArr)) {
            Db::table('biz_topic')->where("id in (" . implode(',', $delArr) . ")")->update(array('status' => 0));
        }
        if (!empty($updateArr)) {
            Db::table('biz_topic')->where("id in (" . implode(',', $updateArr) . ")")->update(array('status' => 1));
        }
        $_arr = array_diff($info, $info_new);
        if (!empty($_arr)) {
            $_arrAdd = array();
            foreach ($_arr as $k => $v) {
                array_push($_arrAdd, array('b_id' => $this->bizId, 'topics' => $v));
            }
            if (!empty($_arrAdd)) {
                Db::table('biz_topic')->insertAll($_arrAdd);
            }
        }
        return array('status' => true);
    }

    function getCopywriting()
    {
        $info = Db::table('biz_copywriting')->field('id,context discribe')->where(array('b_id' => $this->bizId))->select();
        return array('status' => true, 'info' => $info);
    }

    function setCopywriting()
    {
        $add_info = input('post.add_info');
        $del_info = input('post.del_info');
        if (!empty($del_info)) {
            $delId = implode(',', $del_info);
            Db::table('biz_copywriting')->where("id in (" . $delId . ")")->delete();
        }
        if (!empty($add_info)) {
            $addArr = array();
            foreach ($add_info as $k => $v) {
                if ($v['id'] == 0) {
                    array_push($addArr, array('context' => $v['discribe'], 'b_id' => $this->bizId));
                } else {
                    Db::table('biz_copywriting')->where(array('id' => $v['id']))->update(array('context' => $v['discribe']));
                }
            }
            if (!empty($addArr)) {
                Db::table('biz_copywriting')->insertAll($addArr);
            }
        }
        return array('status' => true);
    }

    function getVideos()
    {
        $num = 5;
        $numMsg = '视频数量不得超过5条！';
        $info = Db::table('biz_video')->where(array('b_id' => $this->bizId))->column('video_url');
        return array('status' => true, 'info' => $info, 'num' => $num, 'numMsg' => $numMsg);
    }

    function addVideos()
    {
        $info = input('post.info');
        $_arr = array();
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                $v = str_replace(array('"', '\\'), "", $v);
                array_push($_arr, array('b_id' => $this->bizId, 'video_url' => $v));
            }
        }
        if (!empty($_arr)) {
            Db::table('biz_video')->insertAll($_arr);
        }
        return array('status' => true);
    }

    function getQrcode()
    {
        $merchandId = $this->bizId;
        $bizinfo = Db::table('biz')->field('biz_title')->where(array('id'=>$this->bizId))->find();
        if (!empty($merchandId)) {
            # 图片名称
            $filename = 'qrcodes' . $merchandId . '.png';
            # 绝对路径
            $file = ROOT_PATH . 'static/img/bizQrCode/' . $filename;
            # 判断是否已经存在,存在直接放回 , 不存在接口获取

//                    "path" => urlencode("pages/index/shop_info?id=" . $merchandId),
            //"path" => urlencode("pages/index/video_share?m_id=" . $merchandId."&source=2"),
            if (!file_exists($file)) {
                $postUrl = 'https://developer.toutiao.com/api/apps/qrcode';
                $_arr = array(
                    "access_token" => $this->getAccessToken(),
                    "appname" => "douyin",
                    "path" => urlencode("pages/index/video_share?m_id=" . $merchandId."&source=2"),
                    "width" => 430,
                    "line_color" => ["r" => 0, "g" => 0, "b" => 0],
                    "background" => ["r" => 255, "g" => 255, "b" => 255],
                    "set_icon" => true
                );
                $curl = new Curl();
                $res = $curl->post($postUrl, $_arr, 'json');
                $a = file_put_contents($file, $res);
                # 图片访问地址
                $retFile = imgUrl('static/img/bizQrCode/' . $filename, true);
                return array('status'=>true,'url'=>$retFile,'biz_title'=>$bizinfo['biz_title']);
            }else{
                # 图片访问地址
                $retFile = imgUrl('static/img/bizQrCode/' . $filename, true);
                return array('status'=>true,'url'=>$retFile,'biz_title'=>$bizinfo['biz_title']);
            }
        }
    }

    function getAccessToken()
    {
        $postUrl = 'https://developer.toutiao.com/api/apps/v2/token';
        $_arr = array(
            "appid" => config('ecarcoo.toutiao_Appid'),
            "secret" => config('ecarcoo.toutiao_AppSecret'),
            "grant_type" => "client_credential"
        );
        $curl = new Curl();
        $res = $curl->post($postUrl, $_arr, 'json');
        $resData = json_decode($res, true);
        $accessToken = '';
        if (!empty($resData) && $resData['err_no'] == 0) {
            $accessToken = $resData['data']['access_token'];
        }
        return $accessToken;
    }

    function share_id()
    {
        $share_id = '';
        $client_token_url = 'https://open.douyin.com/oauth/client_token/';
        $order = [
            'client_key' => 'awat9we7skb9anza',
            'client_secret' => 'f95d24fec8b15c2d5b9e2ac91fcda68a',
            'grant_type' => 'client_credential'
        ];
        $curl = new Curl();
        $res = $curl->post($client_token_url, $order, 'form');
        $resData = json_decode($res, true);
        if (!empty($resData)) {
            if ($resData['data']['error_code'] == 0) {
                $token = $resData['data']['access_token'];
                $url = 'https://open.douyin.com/share-id/?access_token=' . $token . '&need_callback=true';
                $re = $curl->get($url);
                $reData = json_decode($re, true);
                if ($reData['data']['error_code'] == 0) {
                    $share_id = $reData['data']['share_id'];
                }
            }
        }
        return array("status" => true, 'share_id' => $share_id);;
    }
}
